package com.dgshanger.sanhxiaofeisc.ui.person

import android.Manifest
import android.annotation.SuppressLint
import android.content.DialogInterface
import android.content.Intent
import android.os.Environment
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import cn.jpush.android.api.JPushInterface
import com.blankj.utilcode.util.PermissionUtils
import com.dgshanger.sanhxiaofeisc.BuildConfig
import com.dgshanger.sanhxiaofeisc.R
import com.dgshanger.sanhxiaofeisc.adapter.PersonItemAdapter
import com.dgshanger.sanhxiaofeisc.common.Constants
import com.dgshanger.sanhxiaofeisc.dialog.ChooseImageDialogWrapper
import com.dgshanger.sanhxiaofeisc.entity.PersonalItemEntity
import com.dgshanger.sanhxiaofeisc.entity.UserEntity
import com.dgshanger.sanhxiaofeisc.mvp.contract.PersonContract
import com.dgshanger.sanhxiaofeisc.mvp.presenter.PersonPresenter
import com.dgshanger.sanhxiaofeisc.ui.home.utils.ImageLoader
import com.dgshanger.sanhxiaofeisc.ui.login.LoginActivity
import com.xx.baseuilibrary.mvp.lcec.BaseMvpLcecFragment
import com.xx.baseutilslibrary.common.ImageChooseHelper
import kotlinx.android.synthetic.main.fragment_person.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * PersonFragment
 * 沉迷学习不能自拔
 * Describe：
 * Created by 雷小星🍀 on 2018/4/10 18:09.
 */
class PersonFragment : BaseMvpLcecFragment<SwipeRefreshLayout, UserEntity, PersonContract.Model, PersonContract.View, PersonPresenter>(),
        PersonContract.View, View.OnClickListener {

    override fun editAvatarSuccess() {
        loadData(true)
    }

    override fun loadData(refresh: Boolean) {
        presenter.getUserInfo()
    }

    override fun setRefreshing(refreshing: Boolean) {
        contentView.post {
            contentView.isRefreshing = refreshing
        }
    }

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        EventBus.getDefault().unregister(this)
        super.onStop()
    }

    @SuppressLint("SetTextI18n")
    override fun setData(data: UserEntity?) {
        EventBus.getDefault().post("用户资料加载成功")
        showContent()
        //设置极光别名
        JPushInterface.setAlias(mContext, data!!.show_id, null)
        data.apply {
            tv_user_id.text = "ID:$show_id"
            tv_user_nickname.text = nick_name
            tv_user_level.text = vip_name
            tv_by.text = if (TextUtils.isEmpty(recommend_user_name)) "" else "By $recommend_user_name"
            ImageLoader.loadAvatar(mContext, iv_user_head, avatar)
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onMessageChange(showMessage: String) {
        when (showMessage) {
            "showMessage" -> ib_message.setImageResource(R.drawable.youxiaoxi_)
            "readMsg" -> ib_message.setImageResource(R.drawable.shaoxi_)
        }
    }

    override fun createPresenter(): PersonPresenter = PersonPresenter()

    override fun onClick(v: View?) {
        if (!Constants.isLogin()) {
            showToast("请登录")
            startActivity(LoginActivity::class.java)
            return
        }
        when (v?.id) {
            R.id.tv_user_nickname -> //修改昵称
                startActivity(EditNicknameActivity::class.java)
            R.id.ib_message -> //消息中心
                startActivity(MessageActivity::class.java)
            R.id.iv_user_head ->//修改头像
                showEditAvatarDialog()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        imageChooseHelper.onActivityResult(requestCode, resultCode, data)
    }

    /**
     * 显示修改头像弹窗
     */
    private fun showEditAvatarDialog() {
        //选图弹窗
        //请求相机和内存读取权限
        PermissionUtils.permission(Manifest.permission.CAMERA, Manifest.permission_group.STORAGE)
                .callback(object : PermissionUtils.SimpleCallback {
                    override fun onGranted() {
                        //被给予权限,调起选图弹窗
                        ChooseImageDialogWrapper(imageChooseHelper)
                                .showChooseImage()
                    }

                    override fun onDenied() {
                        //被拒绝
                        showToast("拒绝给予权限会导致该功能不能正常使用")
                    }
                })
                .rationale { shouldRequest -> shouldRequest.again(true) }
                .request()
    }

    override fun getFragmentLayoutId(): Int = R.layout.fragment_person

    private lateinit var personItemAdapter: PersonItemAdapter

    override fun initView(view: View?) {
        super.initView(view)
        recyclerView.layoutManager = object : LinearLayoutManager(mContext) {
            override fun canScrollVertically(): Boolean {
                return false//禁止滑动
            }
        }
        personItemAdapter = PersonItemAdapter()
        recyclerView.adapter = personItemAdapter
        personItemAdapter.upDate(PersonalItemEntity.list)
    }

    override fun onResume() {
        super.onResume()

        tv_user_id.visibility = if (Constants.isLogin()) View.VISIBLE else View.INVISIBLE
        tv_user_level.visibility = if (Constants.isLogin()) View.VISIBLE else View.INVISIBLE
        tv_by.visibility = if (Constants.isLogin()) View.VISIBLE else View.INVISIBLE
        if (!Constants.isLogin()) {
            //未登录显示未登录布局.
            iv_user_head.setImageResource(R.color.colorDivler)
            tv_user_nickname.text = "未登录用户"
        } else {
            //登录状态才获取数据
            loadData(true)
        }
    }

    override fun initEvent(view: View?) {

        personItemAdapter.setOnItemClickListener { position, entity ->
            //跳转到对应Activity
            if (!Constants.isLogin()) {
                showToast("请登录")
                startActivity(LoginActivity::class.java)
                return@setOnItemClickListener
            }

            if (entity.getaClass() != null) {
                startActivity(entity.getaClass()!!)
            } else {
                AlertDialog.Builder(mContext)
                        .setMessage("确定要退出登录?")
                        .setPositiveButton(getString(R.string.sure), object : DialogInterface.OnClickListener {
                            override fun onClick(dialog: DialogInterface?, which: Int) {
                                //关闭MainActivity
                                Constants.putToken(null)//退出清除token
                                Constants.putUserEntity(null)
                                startActivity(LoginActivity::class.java)
                            }
                        })
                        .setNegativeButton(getString(R.string.cancel), null)
                        .create()
                        .show()
            }
        }

        tv_user_nickname.setOnClickListener(this)
        ib_message.setOnClickListener(this)
        iv_user_head.setOnClickListener(this)

        //刷新
        contentView.setOnRefreshListener {
            getPresenter().getUserInfo()
        }
    }

    private lateinit var imageChooseHelper: ImageChooseHelper

    override fun initData() {

        contentView.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorAccent))

        imageChooseHelper = ImageChooseHelper.Builder()
                .setUpFragment(this)
                .setAuthority("${BuildConfig.APPLICATION_ID}.fileprovider")//设置文件提供者
                .setDirPath(Environment.getExternalStorageDirectory().absolutePath + "/" + BuildConfig.APPLICATION_ID)//设置文件存储路径
                .isCrop(true)//开启裁剪
                .setCompressQuality(100)//压缩质量[1,100]
                .setSize(120, 120)//裁剪尺寸
                .setOnFinishChooseAndCropImageListener { bitmap, file ->
                    //显示选好得图片
                    iv_user_head.setImageBitmap(bitmap)
                    //上传头像
                    presenter.fileStore(file)
                }
                .create()
    }
}